var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var path = require('path');
var fs = require('fs');
var colors = require('colors');
var morgan = require('morgan');
var favicon = require('express-favicon');
var app = express();
var port = 3003;
var mongooseDB = require('./config/mongoose.js');
var settings = require('./settings');

mongooseDB();

colors.setTheme({
    info: 'green',
    data: 'blue',
    warn: 'yellow',
    debug: 'magenta',
    error: 'red'
});

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
    secret: settings.secret,
    resave: false,
    saveUninitialized: true,
    key: settings.db.key,
    cookie: {maxAge: settings.cookie.maxAge},
    store: new MongoStore({
        url: settings.db.url
    })
}));
app.use(flash());
app.use(favicon(__dirname+'/public/favicon.jpg'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(morgan('combined', {stream: fs.createWriteStream('access.log')}));

// //允许跨域
// app.use((req,res,next)=>{
//   res.setHeader("Access-Control-Allow-Origin", "*");
//   res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//   next();
// });

app.use('/test', require('./routes/test'));//Test

app.use('/', require('./routes/index'));//首页
app.use('/reg', require('./routes/reg'));//注册
app.use('/logout', require('./routes/logout'));//登出
app.use('/login', require('./routes/login'));//登录
app.use('/post', require('./routes/post'));//发表文章
app.use('/user', require('./routes/user'));//用户博客列表

app.use('/article', require('./routes/article'));//博客详细
app.use('/edit', require('./routes/edit'));//编辑博客
app.use('/reprint', require('./routes/reprint'));//转载
app.use('/remove', require('./routes/remove'));//删除博客

app.use('/archive', require('./routes/archive'));//归档分类
app.use('/tags', require('./routes/tags'));//标签
app.use('/search', require('./routes/search'));//搜索
app.use('/links', require('./routes/links'));//友情链接
app.use('/upload', require('./routes/upload'));//上传图片

app.use('/api', require('./routes/api'));//API

// error handlers
app.use(function (req, res, next) {
    res.sendStatus(404);
});


var errorLog = fs.createWriteStream('error.log');
app.use(function (err, req, res, next) {
    console.log('Log error:', err);
    errorLog.write([req.url, '['+new Date()+']', err.stack, '\n'].join('\n'));
    next(err);
});

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    console.log('Res error:', err);
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.listen(port, function () {
    console.log(`\n\nJKBlogMongoose port:${port} Time:${new Date().toLocaleTimeString()}`);
});